import requests
import argparse
import sys


def login(url):
    """登录获取令牌"""
    login_url = f"{url}/api/base/LoginWithoutCaptcha"
    login_data = {
        "username": "fxxian",
        "password": "fxxian@2024"
    }
    
    try:
        headers = {
            "Content-Type": "application/json"
        }
        response = requests.post(login_url, json=login_data, headers=headers)
        response.raise_for_status()
        result = response.json()
        
        if result.get("code") == 0 and "data" in result and "token" in result["data"]:
            return result["data"]["token"]
        else:
            print(f"登录失败: {result.get('msg', '未知错误')}")
            sys.exit(1)
    except requests.exceptions.RequestException as e:
        print(f"请求错误: {e}")
        sys.exit(1)


def update_pipeline_status(url, token, pipeline_id, build_no, reinforce_status):
    """更新流水线加固状态"""
    update_url = f"{url}/api/plh/updateHistoryReinforce"
    headers = {
        "X-token": token,
        "Content-Type": "application/json"
    }
    update_data = {
        "pipeline_id": pipeline_id,
        "build_no": str(build_no),  # 转换为字符串
        "reinforce_status": reinforce_status
    }
    try:
        response = requests.put(update_url, json=update_data, headers=headers)
        response.raise_for_status()
        result = response.json()
        
        if result.get("code") == 0:
            print(f"成功更新流水线 {pipeline_id} 构建号 {build_no} 的加固状态为 {reinforce_status}")
            return True
        else:
            print(f"更新失败: {result.get('msg', '未知错误')}")
            return False
    except requests.exceptions.RequestException as e:
        print(f"请求错误: {e}")
        return False


def main():
    # 创建参数解析器
    parser = argparse.ArgumentParser(description="更新流水线加固状态")
    parser.add_argument("--pipeline-id", type=int, required=True, help="流水线ID")
    parser.add_argument("--build-no", type=int, required=True, help="构建号")
    parser.add_argument("--reinforce-status", type=lambda x: x.lower() == 'true', required=True, help="加固状态(true/false)")
    parser.add_argument("--url", type=str, default="http://10.103.106.162:8080", help="API基础URL")
    
    # 解析命令行参数
    args = parser.parse_args()
    
    # 获取令牌
    token = login(args.url)
    if not token:
        return
    
    # 更新加固状态
    update_pipeline_status(args.url, token, args.pipeline_id, args.build_no, args.reinforce_status)


if __name__ == "__main__":
    main()